<?php
defined('IN_PHPCMS') or exit('No permission resources.');

class index
{

    private $db;
    private $goods_info;
    private $order;
    private $pay_db;
    private $goods_check;
    private $setting;

    public function __construct()
    {
        pc_base::load_app_func('global');
        $this->db = pc_base::load_model('goods_model');
        $this->goods_info = pc_base::load_model('goods_info_model');
        $this->pay_db = pc_base::load_model('pay_payment_model');
        $this->order = pc_base::load_model('goods_order_model');
        $this->goods_check = pc_base::load_model('goods_check_model');
        $this->setting = pc_base::load_model('goods_setting_model');
    }

    public function init()
    {
        if (isset($_GET['siteid'])) {
            $siteid = intval($_GET['siteid']);
        } else {
            $siteid = 1;
        }
        $siteid = $GLOBALS['siteid'] = max($siteid, 1);
        define('SITEID', $siteid);
        $SEO = seo($siteid);
        $result = $this->db->select();
        include template('goods', 'index');
    }

    public function goods_info()
    {
        if (isset($_GET['siteid'])) {
            $siteid = intval($_GET['siteid']);
        } else {
            $siteid = 1;
        }
        $siteid = $GLOBALS['siteid'] = max($siteid, 1);
        define('SITEID', $siteid);
        $SEO = seo($siteid);
        $result = $this->db->get_one(array('id' => trim($_GET['goods_id'])));
        if ($result['ship'] == 2) {
            $result['reserve'] = $this->db->getGoodsNum($result['id']);
        }
        include template('goods', 'info');
    }

    /**
     * 高级选号
     */
    public function customize()
    {
        if (isset($_GET['siteid'])) {
            $siteid = intval($_GET['siteid']);
        } else {
            $siteid = 1;
        }
        $siteid = $GLOBALS['siteid'] = max($siteid, 1);
        define('SITEID', $siteid);
        $SEO = seo($siteid);
        include template('goods', 'customize');
    }

    /**
     * 查询自己购买的订单
     */
    public function search_order()
    {
        if (isset($_GET['siteid'])) {
            $siteid = intval($_GET['siteid']);
        } else {
            $siteid = 1;
        }
        $siteid = $GLOBALS['siteid'] = max($siteid, 1);
        define('SITEID', $siteid);
        $SEO = seo($siteid);
        if ($_POST['order'] || $_POST['qq']) {
            $where['accept_qq'] = trim($_POST['qq']);
//            $where['order_on'] = trim($_POST['order']);
            $where['is_pay'] = 2;
            $goods = $this->order->get_one($where);
            if (!empty($goods)) {
                $ids = $this->getGoodsIds($goods['goods_id'], $goods['number']);
                $goodsInfo = $this->getGoodsList($ids);
            }
        }
        include template('goods', 'order');
    }

    /**
     * 下载订单
     */
    public function down()
    {
        if (!empty($_GET['id'])) {
            $data = $this->order->get_one(array('id' => trim($_GET['id'])));
            $result = $this->getGoodsList($data['goods'], 2);
            $dir = CACHE_PATH . 'bakup/';
            $filename = $dir . $data['order_on'] . '.txt';
            if (!file_exists($filename)) {
                foreach ($result as $key => $val) {
                    $str = $val['username'] . '----' . $val['password'];
                    $data = empty($val['token']) ? $str : $str . '----' . $val['token'];
                    file_put_contents($filename, "{$data}\n", FILE_APPEND);
                }
            }
            $name = date('YmdHis', time()) . '-' . mt_rand(1000, 9999) . '.txt';
            if (!file_exists($filename)) {
                echo "文件找不到";
                exit ();
            }
            $file = fopen($filename, "r");
            Header("Content-type: application/octet-stream");
            Header("Accept-Ranges: bytes");
            Header("Accept-Length: " . filesize($filename));
            Header("Content-Disposition: attachment; filename=" . $name);
            echo fread($file, filesize($filename));
            fclose($file);
            unlink($filename);
            exit ();
        }
        showmessage(L('数据错误'), HTTP_REFERER);
    }

    /**
     * 发起支付
     */
    public function alipay()
    {
        if (isset($_POST['type'])) {
            header("Content-type:text/html;charset=utf-8");
            $out_trade_no = getOrder();
            $data['goods_id'] = trim($_POST['goods_id']);
            $goodsInfo = $this->getGoodsPrice($data['goods_id']);
            $data['goods_name'] = trim($_POST['goods_name']);
            $data['number'] = trim($_POST['goods_number']);
            $data['price'] = $goodsInfo['price'] * $data['number'];
            $data['accept_qq'] = trim($_POST['qq']);
            $data['pay_type'] = 1;
            $data['is_deny'] = 0;
            $data['goods'] = $this->getGoodsIds($data['goods_id'], $data['number']);
            $data['is_pay'] = 1;
            $data['order_on'] = $out_trade_no;
            if (empty($data['accept_qq']) || !preg_match('/[1-9][0-9]{4,}/', $data['accept_qq'])) {
                showmessage(L('联系QQ不能为空或QQ不对', array(), 'goods'), HTTP_REFERER);
            }
            if (empty($data['goods'])) {
                showmessage(L('库存不够', array(), 'goods'), HTTP_REFERER);
            }
            $order_id = $this->order->create($data);
            if ($order_id) {
                $query = [
                    'title' => $order_id,
                    'optEmail' => $this->getPayEmail(),
                    'payAmount' => $data['price'],
                ];
                $href = 'http://' . $_SERVER['HTTP_HOST'] . '/alidirectV2/index.php?' . http_build_query($query);
                header('Location:' . $href);
            }
            showmessage(L('goods_order_add_error', array(), 'goods'), HTTP_REFERER);
        }
        showmessage(L('error', array(), 'goods'), HTTP_REFERER);
    }

    /**
     * 获取邮箱
     * @return mixed
     */
    private function getPayEmail()
    {
        $result = $this->pay_db->get_one(array('pay_code' => 'Alidirect', 'is_online' => 1));
        return json_decode($result['config'], true)['alidirect_account']['value'];
    }

    /**
     * 帮助页面
     */
    public function help()
    {
        if (isset($_GET['siteid'])) {
            $siteid = intval($_GET['siteid']);
        } else {
            $siteid = 1;
        }
        $siteid = $GLOBALS['siteid'] = max($siteid, 1);
        define('SITEID', $siteid);
        $SEO = seo($siteid);
        include template('goods', 'help');
    }

    /**
     * 获取支付账号信息
     * @return mixed
     */
    private function getPayConfig()
    {
        header("Content-type:text/html;charset=utf-8");
        $result = $this->pay_db->get_one(array('pay_code' => 'Alipay', 'is_online' => 1));
        $config['name'] = $result['name'];
        $tmpArray = json_decode($result['config'], true);
        $config['alipay_account'] = $tmpArray['alipay_account']['value'];
        $config['alipay_key'] = $tmpArray['alipay_key']['value'];
        $config['alipay_partner'] = $tmpArray['alipay_partner']['value'];
        $config['service_type'] = $tmpArray['service_type']['value'];
        return $config;
    }

    /**
     * 生成签名跳转到支付宝
     * @param $data
     */
    private function setSignToPay($goods)
    {
        $config = $this->getPayConfig();
        $postData['service'] = 'create_direct_pay_by_user';
        $postData['partner'] = $config['alipay_partner'];
        $postData['_input_charset'] = 'utf-8';
        $postData['payment_type'] = $config['service_type'];
        $postData['notify_url'] = $goods['notify_url'];
        $postData['return_url'] = $goods['return_url'];
        $postData['seller_email'] = $config['alipay_account'];
        $postData['out_trade_no'] = $goods['out_trade_no'];
        $postData['subject'] = $goods['subject'];
        $postData['total_fee'] = $goods['total_fee'];
        ksort($postData);
        $url = '';
        foreach ($postData as $key => $val) {
            if ($val) {
                $url .= $key . '=' . $val . "&";
            }
        }
        $url = rtrim($url, '&');
        $sign = md5($url . $config['alipay_key']);
        $result = $url . '&sign=' . $sign;
        header('Location:https://mapi.alipay.com/gateway.do?' . $result);
    }


    public function notify_url()
    {
        file_put_contents(CACHE_PATH . '/notify_url.php', $_POST);
    }

    public function return_url()
    {
        file_put_contents(CACHE_PATH . '/return_url.php', $_POST);
    }

    /**
     * 检查QQ
     */
    public function check()
    {
        if (isset($_GET['siteid'])) {
            $siteid = intval($_GET['siteid']);
        } else {
            $siteid = 1;
        }
        $siteid = $GLOBALS['siteid'] = max($siteid, 1);
        define('SITEID', $siteid);
        $SEO = seo($siteid);
        if ($_POST['act'] == 'sub') {
            $result = preg_split("/[\s,]+/", $_POST['qq']);
            $len = count(array_filter($result));
            $price = $this->getTypePrice($_POST['type']);
            $order_on = getOrder();
            $data['pay_qq'] = trim($_POST['pay_qq']);
            $data['type'] = trim($_POST['type']);
            if (empty($data['pay_qq']) || empty($_POST['qq']) || empty($_POST['type'])) {
                showmessage(L('goods_empty_error', array(), 'goods'), HTTP_REFERER);
            }
            $data['len'] = $len;
            $data['data'] = $_POST['qq'];
            $data['price'] = $price * $len;
            $data['is_pay'] = 1;
            $data['order_on'] = $order_on;
            $data['addtime'] = time();
            $data['updatetime'] = time();
            $goods_id = $this->goods_check->insert($data,true);
            if ($goods_id) {
                $pay['goods_id'] = $goods_id;
                switch ($_POST['type']) {
                    case 1:
                        $pay['goods_name'] = '查冻结';
                        break;
                    case 2:
                        $pay['goods_name'] = '查DNF';
                        break;
                    case 3:
                        $pay['goods_name'] = '查等级Q龄';
                        break;
                }
                $pay['pay_type'] = 1;
                $pay['type'] = 2;
                $pay['is_pay'] = 1;
                $pay['order_on'] = $order_on;
                $pay['number'] = $len;
                $pay['price'] = $data['price'];
                $pay['accept_qq'] = $_POST['pay_qq'];
                $order_id = $this->order->create($pay);
                if ($order_id) {
                    $query = [
                        'title' => $order_id,
                        'optEmail' => $this->getPayEmail(),
                        'payAmount' => $data['price'],
                    ];
                    $href = 'http://' . $_SERVER['HTTP_HOST'] . '/alidirectV2/index.php?' . http_build_query($query);
                    header('Location:' . $href);
                }
                showmessage(L('goods_check_add_error', array(), 'goods'), HTTP_REFERER);
            }
            showmessage(L('goods_check_add_error', array(), 'goods'), HTTP_REFERER);
        }
        include template('goods', 'check');
    }

    /**
     * 获取类型的价格
     * @param $type
     * @return mixed
     */
    private function getTypePrice($type)
    {
        $result = $this->setting->select(array(), '*');
        $data = array();
        foreach ($result as $key => $val) {
            $data[$val['name']] = $val['value'];
        }
        switch ($type) {
            case 1:
                return $data['freeze'];
                break;
            case 2:
                return $data['dnf'];
                break;
            case 3:
                return $data['level'];
                break;
        }
    }

    /**
     * 商品信息
     * @param $goods_id
     * @return mixed
     */
    private function getGoodsPrice($goods_id)
    {
        return $this->db->get_one(array('id' => $goods_id));
    }

    /**
     * 通过goods_id 和数量获取ID编号
     * @param $goods_id
     * @param $number
     * @return string
     */
    private function getGoodsIds($goods_id, $number)
    {
        $where['is_deny'] = 1;
        $where['goods_id'] = $goods_id;
        $result = $this->goods_info->select($where, 'id', $number);
        $ids = '';
        foreach ($result as $key => $val) {
            $ids .= $val['id'] . ",";
        }
        return rtrim($ids, ',');
    }

    /**
     * 获取商品数据
     * @param $ids 通过id获取
     * @param $type 通过type获取购买和未购买号码
     * @return mixed
     */
    private function getGoodsList($ids, $type = 1)
    {
        $where = "is_deny={$type} AND ";
        $where .= "id IN($ids)";
        $result = $this->goods_info->select($where, 'id,goods_id,username,password,token');
        return $result;
    }
}